package main.java.indi.zyj.coderecord;

import java.util.Arrays;
import java.util.Stack;

public class NextGreaterElements2 {

    public int[] nextGreaterElements(int[] nums) {

        Stack<Integer> stack = new Stack<>();
        int len = nums.length;
        int[] res = new int[len];
        Arrays.fill(res, -1);

        for (int i = 0; i < len * 2; i++) {
            while (!stack.isEmpty() && nums[i % len] > nums[stack.peek()]) {
                res[stack.pop()] = nums[i % len];
            }
            stack.push(i % len);
        }

        return res;
    }

}
